package handler

import (
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
	"strconv"
	"time"
	"zk2/globals"
	"zk2/pkg/rabbitMQ"
)

var upgrader = websocket.Upgrader{
	ReadBufferSize:  1024,
	WriteBufferSize: 1024,
}

type ChatHandler struct {
}

func NewChatHandler() *ChatHandler {
	return &ChatHandler{}
}
func (ch *ChatHandler) ChatIm(c *gin.Context) {
	u, _ := c.Get("userId")
	uid, _ := strconv.Atoi(u.(string))
	conn, err := upgrader.Upgrade(c.Writer, c.Request, nil)
	if err != nil {
		return
	}
	node := globals.Node{
		Conn: conn,
		Data: make(chan []byte, 50),
	}
	globals.ClientMap[uid] = node
	fmt.Println(globals.ClientMap)
	go ReadMessage(node)
	go WriteMessage(node)
}
func ReadMessage(node globals.Node) {
	for {
		_, message, err := node.Conn.ReadMessage()
		if err != nil {
			return
		}
		fmt.Println(string(message))
		var msg globals.Message
		json.Unmarshal(message, &msg)
		fmt.Println(msg)
		switch msg.Cmd {
		case 1:
			sendStatus := 1
			if n, ok := globals.ClientMap[msg.DistId]; ok {
				n.Data <- message
			} else {
				sendStatus = 0
			}
			RabbitMq := rabbitMQ.NewRabbitMQSimple("im_save_message")
			newMessage := map[string]interface{}{
				"msg":        msg,
				"sendStatus": sendStatus,
				"create_at":  time.Now().UnixNano(),
			}
			fmt.Println(RabbitMq)
			fmt.Println(newMessage)
		case 2:
		default:

		}
	}
}
func WriteMessage(node globals.Node) {
	for {
		data := <-node.Data
		node.Conn.WriteMessage(websocket.TextMessage, data)
	}
}
